<template>
  <div class="video-list">
    <div class="header">
      <h1>视频列表</h1>
      <el-button @click="refreshList" type="primary" :loading="loading">
        刷新列表
      </el-button>
    </div>
    
    <!-- 视频卡片网格布局 -->
    <div class="video-grid">
      <el-card 
        v-for="video in videos" 
        :key="video.id" 
        class="video-card"
        shadow="hover"
      >
        <div class="video-thumbnail" @click="playVideo(video)">
          <!-- 视频缩略图 -->
          <img 
            :src="getVideoThumbnail(video)" 
            :alt="video.name"
            class="thumbnail-image"
            @error="handleImageError"
          />
          <!-- 播放按钮覆盖层 -->
          <div class="play-overlay">
            <el-icon class="play-icon"><VideoPlay /></el-icon>
          </div>
        </div>
        
        <div class="video-info">
          <h3 class="video-title">{{ video.name || `视频 ${video.id}` }}</h3>
          <p class="video-meta">
            {{ formatDate(video.created_at) }}
          </p>
          <!-- 添加调试信息 -->
          <div class="debug-info" style="font-size: 12px; color: #999; margin: 5px 0;">
            ID: {{ video.id }} | 状态: {{ video.status }} | 路径: {{ video.path }}
          </div>
          <div class="video-actions">
            <el-button 
              type="primary" 
              size="small" 
              @click="playVideo(video)"
            >
              播放
            </el-button>
            <el-button 
              size="small" 
              @click="downloadVideo(video)"
            >
              下载
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteVideo(video)"
            >
              删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty 
      v-if="!loading && videos.length === 0" 
      description="暂无视频"
      :image-size="200"
    />

    <!-- 视频播放对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentVideo?.name || '视频播放'"
      width="80%"
      :before-close="handleDialogClose"
    >
      <div class="video-player-container">
        <video
          v-if="currentVideo"
          ref="videoPlayer"
          :src="getVideoUrl(currentVideo)"
          controls
          preload="metadata"
          class="video-player"
        >
          您的浏览器不支持视频播放。
        </video>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="downloadVideo(currentVideo!)">
            下载视频
          </el-button>
        </div>
        </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import api from '@/api'

interface Video {
  id: string
  name?: string
  created_at: string
  createTime: string
  path?: string
  url?: string
  status?: string
  thumbnail?: string
}

const videos = ref<Video[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentVideo = ref<Video | null>(null)
const videoPlayer = ref<HTMLVideoElement | null>(null)

// 获取视频列表
const fetchVideos = async () => {
  loading.value = true
  try {
    console.log('正在获取视频列表...')
    const response: any = await api.get('/api/videos')
    console.log('视频列表原始响应:', response)
    
    // 处理AxiosResponse对象
    const responseData = response.data || response
    console.log('处理后的响应数据:', responseData)
    
    // 适配不同的响应格式
    if (responseData.success && responseData.data) {
      // 格式1: {success: true, data: [...]}
      videos.value = responseData.data
      console.log('使用格式1，videos.value:', videos.value)
    } else if (responseData.code !== undefined && responseData.code === 0 && responseData.data) {
      // 格式2: {code: 0, data: [...]}
      videos.value = responseData.data
      console.log('使用格式2，videos.value:', videos.value)
    } else if (Array.isArray(responseData)) {
      // 格式3: 直接是数组
      videos.value = responseData
      console.log('使用格式3，videos.value:', videos.value)
    } else {
      console.error('获取视频列表失败: 响应格式不匹配', responseData)
      ElMessage.error('获取视频列表失败')
      return
    }
    
    console.log('最终的视频数量:', videos.value.length)
    console.log('视频详细信息:', videos.value)
    
    // 添加更详细的调试信息
    videos.value.forEach((video, index) => {
      console.log(`视频 ${index + 1}:`, {
        id: video.id,
        name: video.name,
        path: video.path,
        url: video.url,
        created_at: video.created_at,
        status: video.status,
        thumbnail: video.thumbnail
      })
    })
    
    if (videos.value.length === 0) {
      console.warn('视频列表为空')
    }
  } catch (error) {
    console.error('获取视频列表失败:', error)
    ElMessage.error('获取视频列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新列表
const refreshList = () => {
  fetchVideos()
}

// 获取视频缩略图
const getVideoThumbnail = (video: Video) => {
  // 如果后端返回了缩略图URL，使用它
  if (video.thumbnail) {
    return video.thumbnail.startsWith('http') ? video.thumbnail : `http://localhost:3002${video.thumbnail}`
  }
  
  // 尝试多种可能的缩略图路径
  if (video.id) {
    // 首先尝试专门的缩略图
    return `http://localhost:3002/output/${video.id}_thumbnail.jpg`
  }
  
  // 如果没有专门的缩略图，使用默认视频图标
  return ''
}

// 获取视频URL
const getVideoUrl = (video: Video) => {
  if (video.url) {
    return video.url.startsWith('http') ? video.url : `http://localhost:3002${video.url}`
  }
  if (video.path) {
    return video.path.startsWith('http') ? video.path : `http://localhost:3002${video.path}`
  }
  return `http://localhost:3002/output/${video.id}.mp4`
}

// 播放视频
const playVideo = (video: Video) => {
  currentVideo.value = video
  dialogVisible.value = true
}

// 下载视频
const downloadVideo = (video: Video) => {
  const videoUrl = getVideoUrl(video)
  const link = document.createElement('a')
  link.href = videoUrl
  link.download = video.name || `video_${video.id}.mp4`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('开始下载视频')
}

// 删除视频
const deleteVideo = async (video: Video) => {
  try {
    // 确认删除
    await ElMessageBox.confirm(
      `确定要删除视频 "${video.name || `视频 ${video.id}`}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 执行删除
    await api.delete(`/api/videos/${video.id}`)
    ElMessage.success('视频删除成功')
    
    // 刷新列表
    await fetchVideos()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除视频失败:', error)
      ElMessage.error('删除视频失败')
    }
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  // 设置默认图片
  img.src = ''
}

// 关闭对话框
const handleDialogClose = () => {
  if (videoPlayer.value) {
    videoPlayer.value.pause()
}
  dialogVisible.value = false
  currentVideo.value = null
}

// 组件挂载时获取视频列表
onMounted(() => {
  fetchVideos()
})

// 组件激活时获取视频列表（从其他页面跳转过来时）
onActivated(() => {
  console.log('视频列表页面激活，刷新视频列表')
  fetchVideos()
})
</script>

<style scoped>
.video-list {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.video-card {
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.video-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

.video-thumbnail {
  position: relative;
  width: 100%;
  height: 180px;
  cursor: pointer;
  overflow: hidden;
  background-color: #f0f0f0;
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.video-thumbnail:hover .thumbnail-image {
  transform: scale(1.05);
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.video-thumbnail:hover .play-overlay {
  opacity: 1;
}

.play-icon {
  font-size: 48px;
  color: white;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
}

.video-info {
  padding: 16px;
}

.video-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-meta {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #909399;
}

.video-actions {
  display: flex;
  gap: 8px;
}

.video-player-container {
  display: flex;
  justify-content: center;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-player {
  width: 100%;
  max-height: 70vh;
  outline: none;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
  }
  
  .video-thumbnail {
    height: 140px;
  }
  
  .play-icon {
    font-size: 36px;
  }
}

@media (max-width: 480px) {
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .video-grid {
    grid-template-columns: 1fr;
  }
}
</style>
